package site.kitcheng.springboottest.api.controller;

import com.alibaba.fastjson2.JSON;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import nl.basjes.parse.useragent.UserAgent;
import nl.basjes.parse.useragent.UserAgentAnalyzer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import site.kitcheng.springboottest.infra.constant.BaseConstant;
import site.kitcheng.springboottest.infra.utils.Result;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Base64;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: CaptchaController
 * Package: site.kitcheng.springboottest.api.controller
 * Description:
 *
 * @Author jiangCheng
 * @Create 2025/1/23 15:54
 * @Version 1.0
 */
@RestController
@CrossOrigin
public class CaptchaController {

    @Autowired
    @Qualifier("captchaProducer")
    private Producer captchaProducer;
    @Autowired
    @Qualifier("captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    UserAgentAnalyzer uaAnalyzer;

    @Autowired
    private StringRedisTemplate redisCache;

    @GetMapping("/captchaImage")
    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    public Result getCode() throws IOException
    {
        // 保存验证码信息
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String verifyKey = BaseConstant.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = "math";
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

       redisCache.opsForValue().set(verifyKey, code, BaseConstant.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return Result.fail(e.getMessage());
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("img", Base64.getEncoder().encodeToString(os.toByteArray()));
        hashMap.put("uuid", uuid);
       return Result.success(hashMap);
    }
    @GetMapping("/frequency")
    public Result getFrequency(HttpServletRequest request) {

        String header = request.getHeader("user-agent");
        String remoteAddr = request.getRemoteAddr();


        UserAgent.ImmutableUserAgent parse = uaAnalyzer.parse(header);

        HashMap<Object, Object> map = new HashMap<>();
        map.put("remoteAddr", remoteAddr);
        // 获取所有可用字段
        for (String field : parse.getAvailableFieldNamesSorted()) {
            map.put(field, parse.getValue(field));
            System.out.println(field + ": " + parse.getValue(field));
        }

        return Result.success(map);
    }


}
